const Base = require('./base.js');
const moment = require('moment');

module.exports = class extends Base {
  /**
   * 获取订单列表
   * @return {Promise} []
   */
  async listAction() {
    // const qq = await this.ctx.session('userInfo');
    // think.logger.info(qq);
    let paraObj = {del_flag: '0'};
    const order_status = this.get('order_status');
    const keyword = this.get('keyword');
    const role_name = this.get('role_name');
    const company_id = this.get('company_id');
    const office_id = this.get('office_id');
   
    if (role_name  ==='salesman')
    {
      paraObj.user_id = think.userId;
    }
    else if (role_name  ==='salesmanager')
    {
      paraObj.company_id = company_id;
      paraObj.office_id = office_id;
    }
    if (!think.isEmpty(order_status)) {
      paraObj.order_status = order_status;
    }

    if (!think.isEmpty(keyword)) {
      //paraObj.order_sn =  ['like', `%${keyword}%`];
     // paraObj.consignee =  ['like', `%${keyword}%`];
      //paraObj.postscript =  ['like', `%${keyword}%`];
      paraObj._complex = {'order_sn|consignee|mobile': ['like', '%' + keyword + '%']};
      
    }
    think.logger.info(paraObj);

    const orderList = await this.model('v_sales_order').where(paraObj).page(1, 10).countSelect();
    const newOrderList = [];
    for (const item of orderList.data) {
      // 订单的商品
      item.goodsList = await this.model('csshop_order_goods_sales').where({
        order_id: item.id
      }).select();
      item.goodsCount = 0;
      item.goodsList.forEach(v => {
        item.goodsCount += v.number;
      });

      // 订单状态的处理
      item.order_status_text = await this.model('csshop_order_sales').getOrderStatusText(item.id);

      // 可操作的选项
      item.handleOption = await this.model('csshop_order_sales').getOrderHandleOption(item.id);

      item.province_name = await this.model('csshop_region').where({
        id: item.province
      }).getField('name', true);
      item.city_name = await this.model('csshop_region').where({
        id: item.city
      }).getField('name', true);
      item.district_name = await this.model('csshop_region').where({
        id: item.district
      }).getField('name', true);
      item.full_region = item.province_name + item.city_name + item.district_name;
      
      newOrderList.push(item);
    }
    orderList.data = newOrderList;

    return this.success(orderList);
  }

  /**
   * 获取订单列表
   * @return {Promise} []
   */
  async listStatusAction() {
    const orderList = await this.model('csshop_order_sales').where({
      user_id: think.userId,
      order_status: 9
    }).page(1, 10).countSelect();
    const newOrderList = [];
    for (const item of orderList.data) {
      // 订单的商品
      item.goodsList = await this.model('csshop_order_goods_sales').where({
        order_id: item.id
      }).select();
      item.goodsCount = 0;
      item.goodsList.forEach(v => {
        item.goodsCount += v.number;
      });

      // 订单状态的处理
      item.order_status_text = await this.model('csshop_order_sales').getOrderStatusText(item.id);

      // 可操作的选项
      item.handleOption = await this.model('csshop_order_sales').getOrderHandleOption(item.id);

      item.province_name = await this.model('csshop_region').where({
        id: item.province
      }).getField('name', true);
      item.city_name = await this.model('csshop_region').where({
        id: item.city
      }).getField('name', true);
      item.district_name = await this.model('csshop_region').where({
        id: item.district
      }).getField('name', true);
      item.full_region = item.province_name + item.city_name + item.district_name;

      newOrderList.push(item);
    }
    orderList.data = newOrderList;

    return this.success(orderList);
  }

  /**
   * 获取订单详情
   * @return {Promise} []
   */
  async detailAction() {
    const orderId = this.get('orderId');
    const orderInfo = await this.model('csshop_order_sales').where({
      user_id: think.userId,
      id: orderId
    }).find();

    if (think.isEmpty(orderInfo)) {
      return this.fail('订单不存在');
    }

    orderInfo.province_name = await this.model('csshop_region').where({
      id: orderInfo.province
    }).getField('name', true);
    orderInfo.city_name = await this.model('csshop_region').where({
      id: orderInfo.city
    }).getField('name', true);
    orderInfo.district_name = await this.model('csshop_region').where({
      id: orderInfo.district
    }).getField('name', true);
    orderInfo.full_region = orderInfo.province_name + orderInfo.city_name + orderInfo.district_name;

    const latestExpressInfo = await this.model('csshop_order_express').getLatestOrderExpress(orderId);
    orderInfo.express = latestExpressInfo;

    const orderGoods = await this.model('csshop_order_goods_sales').where({
      order_id: orderId
    }).select();

    // 订单状态的处理
    orderInfo.order_status_text = await this.model('csshop_order_sales').getOrderStatusText(orderId);
    orderInfo.add_time = moment.unix(orderInfo.add_time).format('YYYY-MM-DD HH:mm:ss');
    orderInfo.final_pay_time = moment('001234', 'Hmmss').format('mm:ss');
    // 订单最后支付时间
    if (orderInfo.order_status === 0) {
      // if (moment().subtract(60, 'minutes') < moment(orderInfo.add_time)) {
      orderInfo.final_pay_time = moment('001234', 'Hmmss').format('mm:ss');
      // } else {
      //     //超过时间不支付，更新订单状态为取消
      // }
    }

    // 订单可操作的选择,删除，支付，收货，评论，退换货
    const handleOption = await this.model('csshop_order_sales').getOrderHandleOption(orderId);

    return this.success({
      orderInfo: orderInfo,
      orderGoods: orderGoods,
      handleOption: handleOption
    });
  }

  /**
   * 提交订单
   * @returns {Promise.<void>}
   */
  async submitAction() {
    // 获取收货地址信息和计算运费
    const addressId = this.post('addressId');
    const checkNow = this.post('checkNow');
    const checkedAddress = await this.model('address').where({
      id: addressId
    }).find();
    if (think.isEmpty(checkedAddress)) {
      return this.fail('请选择收货地址');
    }
    const freightPrice = 0.00;
    // 获取要购买的商品
    const checkedGoodsList = await this.model('cart'+ checkNow).where({
      user_id: think.userId,
      session_id: 1,
      checked: 1
    }).select();
    if (think.isEmpty(checkedGoodsList)) {
      return this.fail('请选择商品');
    }
    // 统计商品总价
    let goodsTotalPrice = 0.00;
    for (const cartItem of checkedGoodsList) {
      goodsTotalPrice += cartItem.number * cartItem.retail_price;
    }
    // 获取订单使用的优惠券
    const couponId = this.post('couponId');
    const couponPrice = 0.00;
    if (!think.isEmpty(couponId)) {
      //
    }
    // 订单价格计算
    const orderTotalPrice = goodsTotalPrice + freightPrice - couponPrice; // 订单的总价
    const actualPrice = orderTotalPrice - 0.00; // 减去其它支付的金额后，要实际支付的金额
    const currentTime = parseInt(this.getTime());

    const orderInfo = {
      order_sn: this.model('order').generateOrderNumber(),
      user_id: think.userId,
      // 收货地址和运费
      consignee: checkedAddress.name,
      mobile: checkedAddress.mobile,
      province: checkedAddress.province_id,
      city: checkedAddress.city_id,
      district: checkedAddress.district_id,
      address: checkedAddress.address,
      freight_price: 0.00,
      // 留言
      postscript: this.post('postscript'),
      // 使用的优惠券
      coupon_id: 0,
      coupon_price: couponPrice,
      add_time: currentTime,
      goods_price: goodsTotalPrice,
      order_price: orderTotalPrice,
      actual_price: actualPrice
    };
    // 开启事务，插入订单信息和订单商品
    const orderId = await this.model('order').add(orderInfo);
    orderInfo.id = orderId;
    if (!orderId) {
      return this.fail('订单提交失败');
    }
    // 统计商品总价
    const orderGoodsData = [];
    for (const goodsItem of checkedGoodsList) {
      orderGoodsData.push({
        order_id: orderId,
        goods_id: goodsItem.goods_id,
        goods_sn: goodsItem.goods_sn,
        product_id: goodsItem.product_id,
        goods_name: goodsItem.goods_name,
        list_pic_url: goodsItem.list_pic_url,
        market_price: goodsItem.market_price,
        retail_price: goodsItem.retail_price,
        number: goodsItem.number,
        goods_specifition_name_value: goodsItem.goods_specifition_name_value,
        goods_specifition_ids: goodsItem.goods_specifition_ids
      });
    }
    await this.model('order_goods').addMany(orderGoodsData);
    await this.model('cart' + checkNow).clearBuyGoods();
    return this.success({
      orderInfo: orderInfo
    });
  }
  

  /**
   * 业务提交订单
   * @returns {Promise.<void>}
   */
  async salesSubmitAction() {
    // 获取收货地址信息和计算运费
    // const addressId = this.post('addressId');
    const latitude = this.post('latitude');
    const orderContent = this.post('orderContent');
    const longitude = this.post('longitude');
    const addressLocal = this.post('address');
    think.logger.info('latitude=' + latitude);
    think.logger.info('orderContent=' + orderContent);
    think.logger.info('longitude=' + longitude);
    let restName = '';
    var orderInfo = {
      totalAmount: 0,
      gps_lon: longitude,
      gps_lat: latitude,
      postscript: orderContent,
      freight_price: 0.00,
      // 使用的优惠券
      coupon_id: 0,
      coupon_price: 0,
      goods_price: 0,
      order_price: 0,
      order_status: 9,
      actual_price: 0
    };

    var myarg = orderContent.split(/[(\r\n)\r\n]+/); // 对textarea内的数据按行分割
    const detailList = [];
    for (var i = 0; i < 6; i++) {
      var aa = myarg[i].split(':');
      if (aa.length === 1)
        aa = myarg[i].split('：');

      if (aa.length === 1) {
        return this.fail('第' + (i + 1) + '行输入数据有问题，请检查！');
      }
      if (i === 0) {
        // orderInfo.orderId = "CS28-" + userInfo.loginName + "-" + aa[1] + "-" + now;
        orderInfo.remark = aa[1];
      } else if (i === 1) {
        restName = aa[1];
        orderInfo.rest_name = aa[1];
      } else if (i === 2) {
        orderInfo.address = aa[1];
      } else if (i === 3) {
        var sp = aa[1].split(',');
        for (var j = 0; j < sp.length; j++) {
          var sp2 = sp[j].split('-');
          if (sp2.length === 1) {
            return this.fail('商品，第' + j + '个，输入数据有问题，请检查！');
          }

          // 判断商品是否可以购买
          let goodsInfo = await this.model('csshop_goods').where({
            name: ['like', '%' + sp2[0] + '%'],
            goods_unit: sp2[2]
          }).find();
          if (think.isEmpty(goodsInfo) || goodsInfo.is_delete === 1) {
            return this.fail(400, '商品已下架');
          }

          // 取得规格的信息,判断规格库存
          let productInfo = await this.model('csshop_product').where({
            goods_id: goodsInfo.id
          }).find();
          if (think.isEmpty(productInfo) || productInfo.goods_number < sp2[1]) {
            return this.fail(400, '库存不足');
          }
          orderInfo.actual_price += parseFloat(sp2[3]) * parseInt(sp2[1]);
          orderInfo.goods_price += productInfo.retail_price * parseInt(sp2[1]);

          detailList.push({
            goods_id: goodsInfo.id,
            product_id: productInfo.id,
            goods_sn: productInfo.goods_sn,
            goods_name: goodsInfo.name,
            list_pic_url: goodsInfo.list_pic_url,
            number: sp2[1],
            user_id: think.userId,
            retail_price: sp2[3],
            market_price: productInfo.retail_price,
            goods_specifition_name_value: [],
            goods_specifition_ids: productInfo.goods_specification_ids,
            checked: 1
          });

        }
      } else if (i === 4) {
        let laoban = aa[1].split('-');
        think.logger.info('longitude=' + laoban[1].length);
        // if (laoban[1].length < 2)
        orderInfo.consignee = laoban[1] + ' ' + aa[0];
        orderInfo.mobile = laoban[0];
      } else if (i === 5) {
        let salesman = aa[1].split('-');

        orderInfo.sales_user = salesman[0];
        orderInfo.sales_mobile = salesman[1];
      }
    }

    const checkedAddress = await this.model('csshop_address').where({
      mobile: orderInfo.mobile
    }).find();
    if (think.isEmpty(checkedAddress)) {
      //则保存此次的地址信息
      //20 广东省   18 湖北省   10 上海市 2 北京
      let pro = addressLocal.substring(0, addressLocal.indexOf('省') + 1);
      const proAdd = await this.model('csshop_region').where({
        name: pro
      }).find();
      let proCity = addressLocal.substring(addressLocal.indexOf('省') + 1, addressLocal.indexOf('市') + 1);
      const cityAdd = await this.model('csshop_region').where({
        name: proCity
      }).find();
      let proArea = addressLocal.substring(addressLocal.indexOf('市') + 1, addressLocal.indexOf('区') + 1);
      const areaAdd = await this.model('csshop_region').where({
        name: proArea
      }).find();

      orderInfo.province = proAdd.id;
      orderInfo.city = cityAdd.id;
      orderInfo.district = areaAdd.id;

      think.logger.info(checkedAddress);
      think.logger.info('test adddress proAdd.id ' + proAdd.id);
      const addressData = {
        name: orderInfo.name,
        mobile: orderInfo.mobile,
        province_id: proAdd.id,
        city_id: cityAdd.id,
        district_id: areaAdd.id,
        address: orderInfo.address,
        remark: restName + ' ' + addressLocal,
        user_id: this.getLoginUserId(),
        is_default: 1
      };
      let addressId = await this.model('csshop_address').add(addressData);
    } else {
      think.logger.info('test adddress ' + checkedAddress.province_id);
      orderInfo.province = checkedAddress.province_id;
      orderInfo.city = checkedAddress.city_id;
      orderInfo.district = checkedAddress.district_id;
    }


    // 订单价格计算
    // const orderTotalPrice = goodsTotalPrice + freightPrice - couponPrice; // 订单的总价
    //const actualPrice = orderTotalPrice - 0.00; // 减去其它支付的金额后，要实际支付的金额
    const currentTime = parseInt(this.getTime() / 1000);

    orderInfo.order_price = orderInfo.actual_price;

    think.logger.info('--------------------------------');
    orderInfo.order_sn = this.model('csshop_order_sales').generateOrderNumber();
    orderInfo.user_id = think.userId;
    orderInfo.add_time = currentTime;
    orderInfo.create_by = think.userId;
    orderInfo.create_date = new Date();
    think.logger.info(orderInfo);


    // 开启事务，插入订单信息和订单商品
    const orderId = await this.model('csshop_order_sales').add(orderInfo);
    orderInfo.id = orderId;
    if (!orderId) {
      return this.fail('订单提交失败');
    }
    // 统计商品总价
    const orderGoodsData = [];
    for (const goodsItem of detailList) {
      orderGoodsData.push({
        order_id: orderId,
        goods_id: goodsItem.goods_id,
        goods_sn: goodsItem.goods_sn,
        product_id: goodsItem.product_id,
        goods_name: goodsItem.goods_name,
        list_pic_url: goodsItem.list_pic_url,
        market_price: goodsItem.market_price,
        retail_price: goodsItem.retail_price,
        number: goodsItem.number,
        // goods_specifition_name_value: goodsItem.goods_specifition_name_value,
        goods_specifition_ids: goodsItem.goods_specifition_ids
      });
    }
    await this.model('csshop_order_goods_sales').addMany(orderGoodsData);
    return this.success({
      orderInfo: orderInfo
    });
  }

  /**
   * 查询物流信息
   * @returns {Promise.<void>}
   */
  async expressAction() {
    const orderId = this.get('orderId');
    if (think.isEmpty(orderId)) {
      return this.fail('订单不存在');
    }
    const latestExpressInfo = await this.model('order_express').getLatestOrderExpress(orderId);
    return this.success(latestExpressInfo);
  }

  /**
   * 提交订单
   * @returns {Promise.<void>}
   */
  async deleteAction() {
    // 获取收货地址信息和计算运费
    const id = this.post('id');
    const dt = new Date();
    const order_status = this.post('order_status');
    const userId = await this.model('csshop_order_sales').where({
      id: id
    }).update({
      update_date: this.formatDateTime(dt),
      update_by: think.userId,
      last_login_ip: '',
      del_flag:'1'
    });
    return this.success({
      orderInfo: userId
    });

  }
  
  /**
   * 提交订单
   * @returns {Promise.<void>}
   */
  async passOrderAction() {
    // 获取收货地址信息和计算运费
    const id = this.post('id');
    const dt = new Date();
    const order_status = this.post('order_status');
    const userId = await this.model('csshop_order_sales').where({
      id: id
    }).update({
      confirm_time: this.formatDateTime(dt),
      order_status: 202,
      confirm_by: think.userId,
      last_login_ip: ''
    });
    return this.success({
      orderInfo: userId
    });

  }

  
  /**
   * 提交订单
   * @returns {Promise.<void>}
   */
  async cancelOrderAction() {
    // 获取收货地址信息和计算运费
    const id = this.post('id');
    const dt = new Date();
    const order_status = this.post('order_status');
    const userId = await this.model('csshop_order_sales').where({
      id: id
    }).update({
      confirm_time: this.formatDateTime(dt),
      order_status: 902,
      confirm_by: think.userId,
      last_login_ip: ''
    });
    return this.success({
      orderInfo: userId
    });

  }
};